import JsEncrypt from 'jsencrypt'
import { KJUR, KEYUTIL, hex2b64 } from 'jsrsasign'
import Vue from 'vue'
import { Message } from 'element-ui'
var RSAEncrypt = {
  // 公钥
  publicKey: `-----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHsFJnAoy4mh1/LKp3OsK+dAPGsxyPrzod0+hi5SE55tEcWDwTpBNwcO/ICnn2VXElEsBGktJrhcC7CyOOY8QeXDpYu99vUc535Yh/Q2NmzkryXZ4BFV6D0NWiGgzYggSlNoVHb3/7GI9LkCjDQyAxrL9xyd+jopJPWHL+O1mVrQIDAQAB
  -----END PUBLIC KEY-----`,
  // 私钥
  privateKey: `-----BEGIN PRIVATE KEY-----
  MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIewUmcCjLiaHX8sqnc6wr50A8azHI+vOh3T6GLlITnm0RxYPBOkE3Bw78gKefZVcSUSwEaS0muFwLsLI45jxB5cOli7329RznfliH9DY2bOSvJdngEVXoPQ1aIaDNiCBKU2hUdvf/sYj0uQKMNDIDGsv3HJ36Oikk9Ycv47WZWtAgMBAAECgYBbJmZkjoDrrZPtD5s/1vhlqlezDjU8jJC04tp0PMnSNKz6podNBmaMnUFmlysRAJquNed2QUEbO9GZlMUA7SIb7CqJEcI6NTFTnuhrPbquFEajQ1GRRBVntPola/wMF4O0M3gVo262764bVnHXefiT7nK2oRBLNSs4v/GbfJ7KnQJBAMX4wkedcdkyNAD0074tHKSpB1MEYTAsPiUQCXpfKFGPUbsbemnOLv4CEHO19mAz1PPmrth+MBDeUE8SxwL48ucCQQCvdgZgj6FszBr0bBHfe5G7fpnrFZ4eM5flnn6f6gXhP81DFrYhwslFAvzmfbuWl1B5zE46W5sdCuNwMUONYLRLAkB4o+O4goB7S/WW05spHBKFYR++fj+/fGaObVxpPw2xzfWPYOpTCbtnPNjLuooeC9fsnZnVAejGjsM/vICcFhrnAkAxLoIHGvuChYugq5Iu9HIa/heiv4J8sLWJFW4k4PIY+0tL3Nfcir7j6zx8Vw333h4epdffn8HQ2DZ8QjLPNCYVAkB/tCqQe9LkhkJhBZ5Eg1PxSKEG2gGHqp5AskkWxg7Ll0YVQkS0DJrPcmcx7FUMsGXOgCEOnrMsA+8FE56UvogJ
  -----END PRIVATE KEY-----
  `,
  SIGN_KEY: '6e4af0a',
  // 签名算法
  ALGORITHM: 'SHA256withRSA',
  encrypt: function(data) {
    const jse = new JsEncrypt()
    jse.setPublicKey(this.publicKey)
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    const result = jse.encrypt(data)
    if (typeof (result) === 'boolean') {
      if (!result) {
        Message({
          message: '公钥不正确,请核对！',
          type: 'warning'
        })
        return null
      }
    }
    return result
  },
  decrypt: function(data) {
    if (typeof (data) !== 'string') {
      Message({
        message: '加密数据不正确,请核对！',
        type: 'warning'
      })
      return null
    }
    const jse = new JsEncrypt()
    jse.setPrivateKey(this.privateKey)
    if (typeof (data) === 'object') {
      data = JSON.stringify(data)
    }
    const result = jse.decrypt(data)
    return result
  },
  // 私钥签名
  rsaSign: function(plaintext) {
    const signature = new KJUR.crypto.Signature({ 'alg': this.ALGORITHM })
    // 来解析密钥
    const priKey = KEYUTIL.getKey(this.privateKey)
    signature.init(priKey)
    // 传入待签明文
    signature.updateString(plaintext)
    const a = signature.sign()
    // 转换成base64，返回
    return hex2b64(a)
  },
  paramSign(config) {
    var encryptParams = config.params
    var method = config.method
    if (method === 'get') {
      if (config.params != null) {
        encryptParams = config.params
      } else {
        encryptParams = {}
      }
    }
    if (method === 'post') {
      if (config.data != null) {
        encryptParams = config.data
      } else {
        encryptParams = {}
      }
    }

    const values = []
    if (typeof (encryptParams) === 'object') {
      if (Object.prototype.toString.call(encryptParams) === '[object Array]') {
        encryptParams.forEach((item) => {
          if (typeof (item) === 'object') {
            for (const encryptParam in item) {
              if (item[encryptParam] !== undefined) {
                values.push(item[encryptParam])
              }
            }
          } else {
            values.push(item)
          }
        })
      } else {
        for (const encryptParam in encryptParams) {
          if (encryptParams[encryptParam] !== undefined) {
            values.push(encryptParams[encryptParam])
          }
        }
      }
    } else {
      if (encryptParams !== undefined) {
        values.push(encryptParams)
      }
    }
    values.sort()
    values.push(this.SIGN_KEY)

    let s = ''
    values.forEach(function(v, i) {
      if (v !== null) {
        s = s + (v) + ''
      }
    })
    // console.log('参与加密参数:' + s)
    return this.rsaSign(s)
  }
}

Vue.prototype.RSAEncrypt = RSAEncrypt
export default RSAEncrypt
